home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 6 / CU Amiga Magazine's Super CD-ROM 06 (1996)(EMAP Images)(GB)(Track 1 of 4)[!][issue 1997-01].iso / cucd / prog / gnu-c / src / gcc-2.7.0-amiga / cpp.info-2 (.txt) < prev    next >
GNU Info File  |  1995-06-15  |  41KB  |  750 lines

  1. This is Info file cpp.info, produced by Makeinfo-1.55 from the input
  2. file cpp.texi.
  3.    This file documents the GNU C Preprocessor.
  4.    Copyright 1987, 1989, 1991, 1992, 1993, 1994, 1995 Free Software
  5. Foundation, Inc.
  6.    Permission is granted to make and distribute verbatim copies of this
  7. manual provided the copyright notice and this permission notice are
  8. preserved on all copies.
  9.    Permission is granted to copy and distribute modified versions of
  10. this manual under the conditions for verbatim copying, provided also
  11. that the entire resulting derived work is distributed under the terms
  12. of a permission notice identical to this one.
  13.    Permission is granted to copy and distribute translations of this
  14. manual into another language, under the above conditions for modified
  15. versions.
  16. File: cpp.info,  Node: Misnesting,  Next: Macro Parentheses,  Prev: Macro Pitfalls,  Up: Macro Pitfalls
  17. Improperly Nested Constructs
  18. ............................
  19.    Recall that when a macro is called with arguments, the arguments are
  20. substituted into the macro body and the result is checked, together with
  21. the rest of the input file, for more macro calls.
  22.    It is possible to piece together a macro call coming partially from
  23. the macro body and partially from the actual arguments.  For example,
  24.      #define double(x) (2*(x))
  25.      #define call_with_1(x) x(1)
  26. would expand `call_with_1 (double)' into `(2*(1))'.
  27.    Macro definitions do not have to have balanced parentheses.  By
  28. writing an unbalanced open parenthesis in a macro body, it is possible
  29. to create a macro call that begins inside the macro body but ends
  30. outside of it.  For example,
  31.      #define strange(file) fprintf (file, "%s %d",
  32.      ...
  33.      strange(stderr) p, 35)
  34. This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!
  35. File: cpp.info,  Node: Macro Parentheses,  Next: Swallow Semicolon,  Prev: Misnesting,  Up: Macro Pitfalls
  36. Unintended Grouping of Arithmetic
  37. .................................
  38.    You may have noticed that in most of the macro definition examples
  39. shown above, each occurrence of a macro argument name had parentheses
  40. around it.  In addition, another pair of parentheses usually surround
  41. the entire macro definition.  Here is why it is best to write macros
  42. that way.
  43.    Suppose you define a macro as follows,
  44.      #define ceil_div(x, y) (x + y - 1) / y
  45. whose purpose is to divide, rounding up.  (One use for this operation is
  46. to compute how many `int' objects are needed to hold a certain number
  47. of `char' objects.)  Then suppose it is used as follows:
  48.      a = ceil_div (b & c, sizeof (int));
  49. This expands into
  50.      a = (b & c + sizeof (int) - 1) / sizeof (int);
  51. which does not do what is intended.  The operator-precedence rules of C
  52. make it equivalent to this:
  53.      a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  54. But what we want is this:
  55.      a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  56. Defining the macro as
  57.      #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  58. provides the desired result.
  59.    However, unintended grouping can result in another way.  Consider
  60. `sizeof ceil_div(1, 2)'.  That has the appearance of a C expression
  61. that would compute the size of the type of `ceil_div (1, 2)', but in
  62. fact it means something very different.  Here is what it expands to:
  63.      sizeof ((1) + (2) - 1) / (2)
  64. This would take the size of an integer and divide it by two.  The
  65. precedence rules have put the division outside the `sizeof' when it was
  66. intended to be inside.
  67.    Parentheses around the entire macro definition can prevent such
  68. problems.  Here, then, is the recommended way to define `ceil_div':
  69.      #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  70. File: cpp.info,  Node: Swallow Semicolon,  Next: Side Effects,  Prev: Macro Parentheses,  Up: Macro Pitfalls
  71. Swallowing the Semicolon
  72. ........................
  73.    Often it is desirable to define a macro that expands into a compound
  74. statement.  Consider, for example, the following macro, that advances a
  75. pointer (the argument `p' says where to find it) across whitespace
  76. characters:
  77.      #define SKIP_SPACES (p, limit)  \
  78.      { register char *lim = (limit); \
  79.        while (p != lim) {            \
  80.          if (*p++ != ' ') {          \
  81.            p--; break; }}}
  82. Here Backslash-Newline is used to split the macro definition, which must
  83. be a single line, so that it resembles the way such C code would be
  84. laid out if not part of a macro definition.
  85.    A call to this macro might be `SKIP_SPACES (p, lim)'.  Strictly
  86. speaking, the call expands to a compound statement, which is a complete
  87. statement with no need for a semicolon to end it.  But it looks like a
  88. function call.  So it minimizes confusion if you can use it like a
  89. function call, writing a semicolon afterward, as in `SKIP_SPACES (p,
  90. lim);'
  91.    But this can cause trouble before `else' statements, because the
  92. semicolon is actually a null statement.  Suppose you write
  93.      if (*p != 0)
  94.        SKIP_SPACES (p, lim);
  95.      else ...
  96. The presence of two statements--the compound statement and a null
  97. statement--in between the `if' condition and the `else' makes invalid C
  98. code.
  99.    The definition of the macro `SKIP_SPACES' can be altered to solve
  100. this problem, using a `do ... while' statement.  Here is how:
  101.      #define SKIP_SPACES (p, limit)     \
  102.      do { register char *lim = (limit); \
  103.           while (p != lim) {            \
  104.             if (*p++ != ' ') {          \
  105.               p--; break; }}}           \
  106.      while (0)
  107.    Now `SKIP_SPACES (p, lim);' expands into
  108.      do {...} while (0);
  109. which is one statement.
  110. File: cpp.info,  Node: Side Effects,  Next: Self-Reference,  Prev: Swallow Semicolon,  Up: Macro Pitfalls
  111. Duplication of Side Effects
  112. ...........................
  113.    Many C programs define a macro `min', for "minimum", like this:
  114.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  115.    When you use this macro with an argument containing a side effect,
  116. as shown here,
  117.      next = min (x + y, foo (z));
  118. it expands as follows:
  119.      next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
  120. where `x + y' has been substituted for `X' and `foo (z)' for `Y'.
  121.    The function `foo' is used only once in the statement as it appears
  122. in the program, but the expression `foo (z)' has been substituted twice
  123. into the macro expansion.  As a result, `foo' might be called two times
  124. when the statement is executed.  If it has side effects or if it takes
  125. a long time to compute, the results might not be what you intended.  We
  126. say that `min' is an "unsafe" macro.
  127.    The best solution to this problem is to define `min' in a way that
  128. computes the value of `foo (z)' only once.  The C language offers no
  129. standard way to do this, but it can be done with GNU C extensions as
  130. follows:
  131.      #define min(X, Y)                     \
  132.      ({ typeof (X) __x = (X), __y = (Y);   \
  133.         (__x < __y) ? __x : __y; })
  134.    If you do not wish to use GNU C extensions, the only solution is to
  135. be careful when *using* the macro `min'.  For example, you can
  136. calculate the value of `foo (z)', save it in a variable, and use that
  137. variable in `min':
  138.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  139.      ...
  140.      {
  141.        int tem = foo (z);
  142.        next = min (x + y, tem);
  143.      }
  144. (where we assume that `foo' returns type `int').
  145. File: cpp.info,  Node: Self-Reference,  Next: Argument Prescan,  Prev: Side Effects,  Up: Macro Pitfalls
  146. Self-Referential Macros
  147. .......................
  148.    A "self-referential" macro is one whose name appears in its
  149. definition.  A special feature of ANSI Standard C is that the
  150. self-reference is not considered a macro call.  It is passed into the
  151. preprocessor output unchanged.
  152.    Let's consider an example:
  153.      #define foo (4 + foo)
  154. where `foo' is also a variable in your program.
  155.    Following the ordinary rules, each reference to `foo' will expand
  156. into `(4 + foo)'; then this will be rescanned and will expand into `(4
  157. + (4 + foo))'; and so on until it causes a fatal error (memory full) in
  158. the preprocessor.
  159.    However, the special rule about self-reference cuts this process
  160. short after one step, at `(4 + foo)'.  Therefore, this macro definition
  161. has the possibly useful effect of causing the program to add 4 to the
  162. value of `foo' wherever `foo' is referred to.
  163.    In most cases, it is a bad idea to take advantage of this feature.  A
  164. person reading the program who sees that `foo' is a variable will not
  165. expect that it is a macro as well.  The reader will come across the
  166. identifier `foo' in the program and think its value should be that of
  167. the variable `foo', whereas in fact the value is four greater.
  168.    The special rule for self-reference applies also to "indirect"
  169. self-reference.  This is the case where a macro X expands to use a
  170. macro `y', and the expansion of `y' refers to the macro `x'.  The
  171. resulting reference to `x' comes indirectly from the expansion of `x',
  172. so it is a self-reference and is not further expanded.  Thus, after
  173.      #define x (4 + y)
  174.      #define y (2 * x)
  175. `x' would expand into `(4 + (2 * x))'.  Clear?
  176.    But suppose `y' is used elsewhere, not from the definition of `x'.
  177. Then the use of `x' in the expansion of `y' is not a self-reference
  178. because `x' is not "in progress".  So it does expand.  However, the
  179. expansion of `x' contains a reference to `y', and that is an indirect
  180. self-reference now because `y' is "in progress".  The result is that
  181. `y' expands to `(2 * (4 + y))'.
  182.    It is not clear that this behavior would ever be useful, but it is
  183. specified by the ANSI C standard, so you may need to understand it.
  184. File: cpp.info,  Node: Argument Prescan,  Next: Cascaded Macros,  Prev: Self-Reference,  Up: Macro Pitfalls
  185. Separate Expansion of Macro Arguments
  186. .....................................
  187.    We have explained that the expansion of a macro, including the
  188. substituted actual arguments, is scanned over again for macro calls to
  189. be expanded.
  190.    What really happens is more subtle: first each actual argument text
  191. is scanned separately for macro calls.  Then the results of this are
  192. substituted into the macro body to produce the macro expansion, and the
  193. macro expansion is scanned again for macros to expand.
  194.    The result is that the actual arguments are scanned *twice* to expand
  195. macro calls in them.
  196.    Most of the time, this has no effect.  If the actual argument
  197. contained any macro calls, they are expanded during the first scan.
  198. The result therefore contains no macro calls, so the second scan does
  199. not change it.  If the actual argument were substituted as given, with
  200. no prescan, the single remaining scan would find the same macro calls
  201. and produce the same results.
  202.    You might expect the double scan to change the results when a
  203. self-referential macro is used in an actual argument of another macro
  204. (*note Self-Reference::.): the self-referential macro would be expanded
  205. once in the first scan, and a second time in the second scan.  But this
  206. is not what happens.  The self-references that do not expand in the
  207. first scan are marked so that they will not expand in the second scan
  208. either.
  209.    The prescan is not done when an argument is stringified or
  210. concatenated.  Thus,
  211.      #define str(s) #s
  212.      #define foo 4
  213.      str (foo)
  214. expands to `"foo"'.  Once more, prescan has been prevented from having
  215. any noticeable effect.
  216.    More precisely, stringification and concatenation use the argument as
  217. written, in un-prescanned form.  The same actual argument would be used
  218. in prescanned form if it is substituted elsewhere without
  219. stringification or concatenation.
  220.      #define str(s) #s lose(s)
  221.      #define foo 4
  222.      str (foo)
  223.    expands to `"foo" lose(4)'.
  224.    You might now ask, "Why mention the prescan, if it makes no
  225. difference?  And why not skip it and make the preprocessor faster?"
  226. The answer is that the prescan does make a difference in three special
  227. cases:
  228.    * Nested calls to a macro.
  229.    * Macros that call other macros that stringify or concatenate.
  230.    * Macros whose expansions contain unshielded commas.
  231.    We say that "nested" calls to a macro occur when a macro's actual
  232. argument contains a call to that very macro.  For example, if `f' is a
  233. macro that expects one argument, `f (f (1))' is a nested pair of calls
  234. to `f'.  The desired expansion is made by expanding `f (1)' and
  235. substituting that into the definition of `f'.  The prescan causes the
  236. expected result to happen.  Without the prescan, `f (1)' itself would
  237. be substituted as an actual argument, and the inner use of `f' would
  238. appear during the main scan as an indirect self-reference and would not
  239. be expanded.  Here, the prescan cancels an undesirable side effect (in
  240. the medical, not computational, sense of the term) of the special rule
  241. for self-referential macros.
  242.    But prescan causes trouble in certain other cases of nested macro
  243. calls.  Here is an example:
  244.      #define foo  a,b
  245.      #define bar(x) lose(x)
  246.      #define lose(x) (1 + (x))
  247.      
  248.      bar(foo)
  249. We would like `bar(foo)' to turn into `(1 + (foo))', which would then
  250. turn into `(1 + (a,b))'.  But instead, `bar(foo)' expands into
  251. `lose(a,b)', and you get an error because `lose' requires a single
  252. argument.  In this case, the problem is easily solved by the same
  253. parentheses that ought to be used to prevent misnesting of arithmetic
  254. operations:
  255.      #define foo (a,b)
  256.      #define bar(x) lose((x))
  257.    The problem is more serious when the operands of the macro are not
  258. expressions; for example, when they are statements.  Then parentheses
  259. are unacceptable because they would make for invalid C code:
  260.      #define foo { int a, b; ... }
  261. In GNU C you can shield the commas using the `({...})' construct which
  262. turns a compound statement into an expression:
  263.      #define foo ({ int a, b; ... })
  264.    Or you can rewrite the macro definition to avoid such commas:
  265.      #define foo { int a; int b; ... }
  266.    There is also one case where prescan is useful.  It is possible to
  267. use prescan to expand an argument and then stringify it--if you use two
  268. levels of macros.  Let's add a new macro `xstr' to the example shown
  269. above:
  270.      #define xstr(s) str(s)
  271.      #define str(s) #s
  272.      #define foo 4
  273.      xstr (foo)
  274.    This expands into `"4"', not `"foo"'.  The reason for the difference
  275. is that the argument of `xstr' is expanded at prescan (because `xstr'
  276. does not specify stringification or concatenation of the argument).
  277. The result of prescan then forms the actual argument for `str'.  `str'
  278. uses its argument without prescan because it performs stringification;
  279. but it cannot prevent or undo the prescanning already done by `xstr'.
  280. File: cpp.info,  Node: Cascaded Macros,  Next: Newlines in Args,  Prev: Argument Prescan,  Up: Macro Pitfalls
  281. Cascaded Use of Macros
  282. ......................
  283.    A "cascade" of macros is when one macro's body contains a reference
  284. to another macro.  This is very common practice.  For example,
  285.      #define BUFSIZE 1020
  286.      #define TABLESIZE BUFSIZE
  287.    This is not at all the same as defining `TABLESIZE' to be `1020'.
  288. The `#define' for `TABLESIZE' uses exactly the body you specify--in
  289. this case, `BUFSIZE'--and does not check to see whether it too is the
  290. name of a macro.
  291.    It's only when you *use* `TABLESIZE' that the result of its expansion
  292. is checked for more macro names.
  293.    This makes a difference if you change the definition of `BUFSIZE' at
  294. some point in the source file.  `TABLESIZE', defined as shown, will
  295. always expand using the definition of `BUFSIZE' that is currently in
  296. effect:
  297.      #define BUFSIZE 1020
  298.      #define TABLESIZE BUFSIZE
  299.      #undef BUFSIZE
  300.      #define BUFSIZE 37
  301. Now `TABLESIZE' expands (in two stages) to `37'.  (The `#undef' is to
  302. prevent any warning about the nontrivial redefinition of `BUFSIZE'.)
  303. File: cpp.info,  Node: Newlines in Args,  Prev: Cascaded Macros,  Up: Macro Pitfalls
  304. Newlines in Macro Arguments
  305. ---------------------------
  306.    Traditional macro processing carries forward all newlines in macro
  307. arguments into the expansion of the macro.  This means that, if some of
  308. the arguments are substituted more than once, or not at all, or out of
  309. order, newlines can be duplicated, lost, or moved around within the
  310. expansion.  If the expansion consists of multiple statements, then the
  311. effect is to distort the line numbers of some of these statements.  The
  312. result can be incorrect line numbers, in error messages or displayed in
  313. a debugger.
  314.    The GNU C preprocessor operating in ANSI C mode adjusts appropriately
  315. for multiple use of an argument--the first use expands all the
  316. newlines, and subsequent uses of the same argument produce no newlines.
  317. But even in this mode, it can produce incorrect line numbering if
  318. arguments are used out of order, or not used at all.
  319.    Here is an example illustrating this problem:
  320.      #define ignore_second_arg(a,b,c) a; c
  321.      
  322.      ignore_second_arg (foo (),
  323.                         ignored (),
  324.                         syntax error);
  325. The syntax error triggered by the tokens `syntax error' results in an
  326. error message citing line four, even though the statement text comes
  327. from line five.
  328. File: cpp.info,  Node: Conditionals,  Next: Combining Sources,  Prev: Macros,  Up: Top
  329. Conditionals
  330. ============
  331.    In a macro processor, a "conditional" is a directive that allows a
  332. part of the program to be ignored during compilation, on some
  333. conditions.  In the C preprocessor, a conditional can test either an
  334. arithmetic expression or whether a name is defined as a macro.
  335.    A conditional in the C preprocessor resembles in some ways an `if'
  336. statement in C, but it is important to understand the difference between
  337. them.  The condition in an `if' statement is tested during the execution
  338. of your program.  Its purpose is to allow your program to behave
  339. differently from run to run, depending on the data it is operating on.
  340. The condition in a preprocessing conditional directive is tested when
  341. your program is compiled.  Its purpose is to allow different code to be
  342. included in the program depending on the situation at the time of
  343. compilation.
  344. * Menu:
  345. * Uses: Conditional Uses.       What conditionals are for.
  346. * Syntax: Conditional Syntax.   How conditionals are written.
  347. * Deletion: Deleted Code.       Making code into a comment.
  348. * Macros: Conditionals-Macros.  Why conditionals are used with macros.
  349. * Assertions::                How and why to use assertions.
  350. * Errors: #error Directive.     Detecting inconsistent compilation parameters.
  351. File: cpp.info,  Node: Conditional Uses,  Next: Conditional Syntax,  Up: Conditionals
  352. Why Conditionals are Used
  353. -------------------------
  354.    Generally there are three kinds of reason to use a conditional.
  355.    * A program may need to use different code depending on the machine
  356.      or operating system it is to run on.  In some cases the code for
  357.      one operating system may be erroneous on another operating system;
  358.      for example, it might refer to library routines that do not exist
  359.      on the other system.  When this happens, it is not enough to avoid
  360.      executing the invalid code: merely having it in the program makes
  361.      it impossible to link the program and run it.  With a
  362.      preprocessing conditional, the offending code can be effectively
  363.      excised from the program when it is not valid.
  364.    * You may want to be able to compile the same source file into two
  365.      different programs.  Sometimes the difference between the programs
  366.      is that one makes frequent time-consuming consistency checks on its
  367.      intermediate data, or prints the values of those data for
  368.      debugging, while the other does not.
  369.    * A conditional whose condition is always false is a good way to
  370.      exclude code from the program but keep it as a sort of comment for
  371.      future reference.
  372.    Most simple programs that are intended to run on only one machine
  373. will not need to use preprocessing conditionals.
  374. File: cpp.info,  Node: Conditional Syntax,  Next: Deleted Code,  Prev: Conditional Uses,  Up: Conditionals
  375. Syntax of Conditionals
  376. ----------------------
  377.    A conditional in the C preprocessor begins with a "conditional
  378. directive": `#if', `#ifdef' or `#ifndef'.  *Note Conditionals-Macros::,
  379. for information on `#ifdef' and `#ifndef'; only `#if' is explained here.
  380. * Menu:
  381. * If: #if Directive.     Basic conditionals using `#if' and `#endif'.
  382. * Else: #else Directive. Including some text if the condition fails.
  383. * Elif: #elif Directive. Testing several alternative possibilities.
  384. File: cpp.info,  Node: #if Directive,  Next: #else Directive,  Up: Conditional Syntax
  385. The `#if' Directive
  386. ...................
  387.    The `#if' directive in its simplest form consists of
  388.      #if EXPRESSION
  389.      CONTROLLED TEXT
  390.      #endif /* EXPRESSION */
  391.    The comment following the `#endif' is not required, but it is a good
  392. practice because it helps people match the `#endif' to the
  393. corresponding `#if'.  Such comments should always be used, except in
  394. short conditionals that are not nested.  In fact, you can put anything
  395. at all after the `#endif' and it will be ignored by the GNU C
  396. preprocessor, but only comments are acceptable in ANSI Standard C.
  397.    EXPRESSION is a C expression of integer type, subject to stringent
  398. restrictions.  It may contain
  399.    * Integer constants, which are all regarded as `long' or `unsigned
  400.      long'.
  401.    * Character constants, which are interpreted according to the
  402.      character set and conventions of the machine and operating system
  403.      on which the preprocessor is running.  The GNU C preprocessor uses
  404.      the C data type `char' for these character constants; therefore,
  405.      whether some character codes are negative is determined by the C
  406.      compiler used to compile the preprocessor.  If it treats `char' as
  407.      signed, then character codes large enough to set the sign bit will
  408.      be considered negative; otherwise, no character code is considered
  409.      negative.
  410.    * Arithmetic operators for addition, subtraction, multiplication,
  411.      division, bitwise operations, shifts, comparisons, and logical
  412.      operations (`&&' and `||').
  413.    * Identifiers that are not macros, which are all treated as zero(!).
  414.    * Macro calls.  All macro calls in the expression are expanded before
  415.      actual computation of the expression's value begins.
  416.    Note that `sizeof' operators and `enum'-type values are not allowed.
  417. `enum'-type values, like all other identifiers that are not taken as
  418. macro calls and expanded, are treated as zero.
  419.    The CONTROLLED TEXT inside of a conditional can include
  420. preprocessing directives.  Then the directives inside the conditional
  421. are obeyed only if that branch of the conditional succeeds.  The text
  422. can also contain other conditional groups.  However, the `#if' and
  423. `#endif' directives must balance.
  424. File: cpp.info,  Node: #else Directive,  Next: #elif Directive,  Prev: #if Directive,  Up: Conditional Syntax
  425. The `#else' Directive
  426. .....................
  427.    The `#else' directive can be added to a conditional to provide
  428. alternative text to be used if the condition is false.  This is what it
  429. looks like:
  430.      #if EXPRESSION
  431.      TEXT-IF-TRUE
  432.      #else /* Not EXPRESSION */
  433.      TEXT-IF-FALSE
  434.      #endif /* Not EXPRESSION */
  435.    If EXPRESSION is nonzero, and thus the TEXT-IF-TRUE is active, then
  436. `#else' acts like a failing conditional and the TEXT-IF-FALSE is
  437. ignored.  Contrariwise, if the `#if' conditional fails, the
  438. TEXT-IF-FALSE is considered included.
  439. File: cpp.info,  Node: #elif Directive,  Prev: #else Directive,  Up: Conditional Syntax
  440. The `#elif' Directive
  441. .....................
  442.    One common case of nested conditionals is used to check for more
  443. than two possible alternatives.  For example, you might have
  444.      #if X == 1
  445.      ...
  446.      #else /* X != 1 */
  447.      #if X == 2
  448.      ...
  449.      #else /* X != 2 */
  450.      ...
  451.      #endif /* X != 2 */
  452.      #endif /* X != 1 */
  453.    Another conditional directive, `#elif', allows this to be abbreviated
  454. as follows:
  455.      #if X == 1
  456.      ...
  457.      #elif X == 2
  458.      ...
  459.      #else /* X != 2 and X != 1*/
  460.      ...
  461.      #endif /* X != 2 and X != 1*/
  462.    `#elif' stands for "else if".  Like `#else', it goes in the middle
  463. of a `#if'-`#endif' pair and subdivides it; it does not require a
  464. matching `#endif' of its own.  Like `#if', the `#elif' directive
  465. includes an expression to be tested.
  466.    The text following the `#elif' is processed only if the original
  467. `#if'-condition failed and the `#elif' condition succeeds.  More than
  468. one `#elif' can go in the same `#if'-`#endif' group.  Then the text
  469. after each `#elif' is processed only if the `#elif' condition succeeds
  470. after the original `#if' and any previous `#elif' directives within it
  471. have failed.  `#else' is equivalent to `#elif 1', and `#else' is
  472. allowed after any number of `#elif' directives, but `#elif' may not
  473. follow `#else'.
  474. File: cpp.info,  Node: Deleted Code,  Next: Conditionals-Macros,  Prev: Conditional Syntax,  Up: Conditionals
  475. Keeping Deleted Code for Future Reference
  476. -----------------------------------------
  477.    If you replace or delete a part of the program but want to keep the
  478. old code around as a comment for future reference, the easy way to do
  479. this is to put `#if 0' before it and `#endif' after it.  This is better
  480. than using comment delimiters `/*' and `*/' since those won't work if
  481. the code already contains comments (C comments do not nest).
  482.    This works even if the code being turned off contains conditionals,
  483. but they must be entire conditionals (balanced `#if' and `#endif').
  484.    Conversely, do not use `#if 0' for comments which are not C code.
  485. Use the comment delimiters `/*' and `*/' instead.  The interior of `#if
  486. 0' must consist of complete tokens; in particular, singlequote
  487. characters must balance.  But comments often contain unbalanced
  488. singlequote characters (known in English as apostrophes).  These
  489. confuse `#if 0'.  They do not confuse `/*'.
  490. File: cpp.info,  Node: Conditionals-Macros,  Next: Assertions,  Prev: Deleted Code,  Up: Conditionals
  491. Conditionals and Macros
  492. -----------------------
  493.    Conditionals are useful in connection with macros or assertions,
  494. because those are the only ways that an expression's value can vary
  495. from one compilation to another.  A `#if' directive whose expression
  496. uses no macros or assertions is equivalent to `#if 1' or `#if 0'; you
  497. might as well determine which one, by computing the value of the
  498. expression yourself, and then simplify the program.
  499.    For example, here is a conditional that tests the expression
  500. `BUFSIZE == 1020', where `BUFSIZE' must be a macro.
  501.      #if BUFSIZE == 1020
  502.        printf ("Large buffers!\n");
  503.      #endif /* BUFSIZE is large */
  504.    (Programmers often wish they could test the size of a variable or
  505. data type in `#if', but this does not work.  The preprocessor does not
  506. understand `sizeof', or typedef names, or even the type keywords such
  507. as `int'.)
  508.    The special operator `defined' is used in `#if' expressions to test
  509. whether a certain name is defined as a macro.  Either `defined NAME' or
  510. `defined (NAME)' is an expression whose value is 1 if NAME is defined
  511. as macro at the current point in the program, and 0 otherwise.  For the
  512. `defined' operator it makes no difference what the definition of the
  513. macro is; all that matters is whether there is a definition.  Thus, for
  514. example,
  515.      #if defined (vax) || defined (ns16000)
  516. would succeed if either of the names `vax' and `ns16000' is defined as
  517. a macro.  You can test the same condition using assertions (*note
  518. Assertions::.), like this:
  519.      #if #cpu (vax) || #cpu (ns16000)
  520.    If a macro is defined and later undefined with `#undef', subsequent
  521. use of the `defined' operator returns 0, because the name is no longer
  522. defined.  If the macro is defined again with another `#define',
  523. `defined' will recommence returning 1.
  524.    Conditionals that test whether just one name is defined are very
  525. common, so there are two special short conditional directives for this
  526. case.
  527. `#ifdef NAME'
  528.      is equivalent to `#if defined (NAME)'.
  529. `#ifndef NAME'
  530.      is equivalent to `#if ! defined (NAME)'.
  531.    Macro definitions can vary between compilations for several reasons.
  532.    * Some macros are predefined on each kind of machine.  For example,
  533.      on a Vax, the name `vax' is a predefined macro.  On other
  534.      machines, it would not be defined.
  535.    * Many more macros are defined by system header files.  Different
  536.      systems and machines define different macros, or give them
  537.      different values.  It is useful to test these macros with
  538.      conditionals to avoid using a system feature on a machine where it
  539.      is not implemented.
  540.    * Macros are a common way of allowing users to customize a program
  541.      for different machines or applications.  For example, the macro
  542.      `BUFSIZE' might be defined in a configuration file for your
  543.      program that is included as a header file in each source file.  You
  544.      would use `BUFSIZE' in a preprocessing conditional in order to
  545.      generate different code depending on the chosen configuration.
  546.    * Macros can be defined or undefined with `-D' and `-U' command
  547.      options when you compile the program.  You can arrange to compile
  548.      the same source file into two different programs by choosing a
  549.      macro name to specify which program you want, writing conditionals
  550.      to test whether or how this macro is defined, and then controlling
  551.      the state of the macro with compiler command options.  *Note
  552.      Invocation::.
  553.    Assertions are usually predefined, but can be defined with
  554. preprocessor directives or command-line options.
  555. File: cpp.info,  Node: Assertions,  Next: #error Directive,  Prev: Conditionals-Macros,  Up: Conditionals
  556. Assertions
  557. ----------
  558.    "Assertions" are a more systematic alternative to macros in writing
  559. conditionals to test what sort of computer or system the compiled
  560. program will run on.  Assertions are usually predefined, but you can
  561. define them with preprocessing directives or command-line options.
  562.    The macros traditionally used to describe the type of target are not
  563. classified in any way according to which question they answer; they may
  564. indicate a hardware architecture, a particular hardware model, an
  565. operating system, a particular version of an operating system, or
  566. specific configuration options.  These are jumbled together in a single
  567. namespace.  In contrast, each assertion consists of a named question and
  568. an answer.  The question is usually called the "predicate".  An
  569. assertion looks like this:
  570.      #PREDICATE (ANSWER)
  571. You must use a properly formed identifier for PREDICATE.  The value of
  572. ANSWER can be any sequence of words; all characters are significant
  573. except for leading and trailing whitespace, and differences in internal
  574. whitespace sequences are ignored.  Thus, `x + y' is different from
  575. `x+y' but equivalent to `x + y'.  `)' is not allowed in an answer.
  576.    Here is a conditional to test whether the answer ANSWER is asserted
  577. for the predicate PREDICATE:
  578.      #if #PREDICATE (ANSWER)
  579. There may be more than one answer asserted for a given predicate.  If
  580. you omit the answer, you can test whether *any* answer is asserted for
  581. PREDICATE:
  582.      #if #PREDICATE
  583.    Most of the time, the assertions you test will be predefined
  584. assertions.  GNU C provides three predefined predicates: `system',
  585. `cpu', and `machine'.  `system' is for assertions about the type of
  586. software, `cpu' describes the type of computer architecture, and
  587. `machine' gives more information about the computer.  For example, on a
  588. GNU system, the following assertions would be true:
  589.      #system (gnu)
  590.      #system (mach)
  591.      #system (mach 3)
  592.      #system (mach 3.SUBVERSION)
  593.      #system (hurd)
  594.      #system (hurd VERSION)
  595. and perhaps others.  The alternatives with more or less version
  596. information let you ask more or less detailed questions about the type
  597. of system software.
  598.    On a Unix system, you would find `#system (unix)' and perhaps one of:
  599. `#system (aix)', `#system (bsd)', `#system (hpux)', `#system (lynx)',
  600. `#system (mach)', `#system (posix)', `#system (svr3)', `#system
  601. (svr4)', or `#system (xpg4)' with possible version numbers following.
  602.    Other values for `system' are `#system (mvs)' and `#system (vms)'.
  603.    *Portability note:* Many Unix C compilers provide only one answer
  604. for the `system' assertion: `#system (unix)', if they support
  605. assertions at all.  This is less than useful.
  606.    An assertion with a multi-word answer is completely different from
  607. several assertions with individual single-word answers.  For example,
  608. the presence of `system (mach 3.0)' does not mean that `system (3.0)'
  609. is true.  It also does not directly imply `system (mach)', but in GNU
  610. C, that last will normally be asserted as well.
  611.    The current list of possible assertion values for `cpu' is: `#cpu
  612. (a29k)', `#cpu (alpha)', `#cpu (arm)', `#cpu (clipper)', `#cpu
  613. (convex)', `#cpu (elxsi)', `#cpu (tron)', `#cpu (h8300)', `#cpu
  614. (i370)', `#cpu (i386)', `#cpu (i860)', `#cpu (i960)', `#cpu (m68k)',
  615. `#cpu (m88k)', `#cpu (mips)', `#cpu (ns32k)', `#cpu (hppa)', `#cpu
  616. (pyr)', `#cpu (ibm032)', `#cpu (rs6000)', `#cpu (sh)', `#cpu (sparc)',
  617. `#cpu (spur)', `#cpu (tahoe)', `#cpu (vax)', `#cpu (we32000)'.
  618.    You can create assertions within a C program using `#assert', like
  619. this:
  620.      #assert PREDICATE (ANSWER)
  621. (Note the absence of a `#' before PREDICATE.)
  622.    Each time you do this, you assert a new true answer for PREDICATE.
  623. Asserting one answer does not invalidate previously asserted answers;
  624. they all remain true.  The only way to remove an assertion is with
  625. `#unassert'.  `#unassert' has the same syntax as `#assert'.  You can
  626. also remove all assertions about PREDICATE like this:
  627.      #unassert PREDICATE
  628.    You can also add or cancel assertions using command options when you
  629. run `gcc' or `cpp'.  *Note Invocation::.
  630. File: cpp.info,  Node: #error Directive,  Prev: Assertions,  Up: Conditionals
  631. The `#error' and `#warning' Directives
  632. --------------------------------------
  633.    The directive `#error' causes the preprocessor to report a fatal
  634. error.  The rest of the line that follows `#error' is used as the error
  635. message.
  636.    You would use `#error' inside of a conditional that detects a
  637. combination of parameters which you know the program does not properly
  638. support.  For example, if you know that the program will not run
  639. properly on a Vax, you might write
  640.      #ifdef __vax__
  641.      #error Won't work on Vaxen.  See comments at get_last_object.
  642.      #endif
  643. *Note Nonstandard Predefined::, for why this works.
  644.    If you have several configuration parameters that must be set up by
  645. the installation in a consistent way, you can use conditionals to detect
  646. an inconsistency and report it with `#error'.  For example,
  647.      #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
  648.          || HASH_TABLE_SIZE % 5 == 0
  649.      #error HASH_TABLE_SIZE should not be divisible by a small prime
  650.      #endif
  651.    The directive `#warning' is like the directive `#error', but causes
  652. the preprocessor to issue a warning and continue preprocessing.  The
  653. rest of the line that follows `#warning' is used as the warning message.
  654.    You might use `#warning' in obsolete header files, with a message
  655. directing the user to the header file which should be used instead.
  656. File: cpp.info,  Node: Combining Sources,  Next: Other Directives,  Prev: Conditionals,  Up: Top
  657. Combining Source Files
  658. ======================
  659.    One of the jobs of the C preprocessor is to inform the C compiler of
  660. where each line of C code came from: which source file and which line
  661. number.
  662.    C code can come from multiple source files if you use `#include';
  663. both `#include' and the use of conditionals and macros can cause the
  664. line number of a line in the preprocessor output to be different from
  665. the line's number in the original source file.  You will appreciate the
  666. value of making both the C compiler (in error messages) and symbolic
  667. debuggers such as GDB use the line numbers in your source file.
  668.    The C preprocessor builds on this feature by offering a directive by
  669. which you can control the feature explicitly.  This is useful when a
  670. file for input to the C preprocessor is the output from another program
  671. such as the `bison' parser generator, which operates on another file
  672. that is the true source file.  Parts of the output from `bison' are
  673. generated from scratch, other parts come from a standard parser file.
  674. The rest are copied nearly verbatim from the source file, but their
  675. line numbers in the `bison' output are not the same as their original
  676. line numbers.  Naturally you would like compiler error messages and
  677. symbolic debuggers to know the original source file and line number of
  678. each line in the `bison' input.
  679.    `bison' arranges this by writing `#line' directives into the output
  680. file.  `#line' is a directive that specifies the original line number
  681. and source file name for subsequent input in the current preprocessor
  682. input file.  `#line' has three variants:
  683. `#line LINENUM'
  684.      Here LINENUM is a decimal integer constant.  This specifies that
  685.      the line number of the following line of input, in its original
  686.      source file, was LINENUM.
  687. `#line LINENUM FILENAME'
  688.      Here LINENUM is a decimal integer constant and FILENAME is a
  689.      string constant.  This specifies that the following line of input
  690.      came originally from source file FILENAME and its line number there
  691.      was LINENUM.  Keep in mind that FILENAME is not just a file name;
  692.      it is surrounded by doublequote characters so that it looks like a
  693.      string constant.
  694. `#line ANYTHING ELSE'
  695.      ANYTHING ELSE is checked for macro calls, which are expanded.  The
  696.      result should be a decimal integer constant followed optionally by
  697.      a string constant, as described above.
  698.    `#line' directives alter the results of the `__FILE__' and
  699. `__LINE__' predefined macros from that point on.  *Note Standard
  700. Predefined::.
  701.    The output of the preprocessor (which is the input for the rest of
  702. the compiler) contains directives that look much like `#line'
  703. directives.  They start with just `#' instead of `#line', but this is
  704. followed by a line number and file name as in `#line'.  *Note Output::.
  705. File: cpp.info,  Node: Other Directives,  Next: Output,  Prev: Combining Sources,  Up: Top
  706. Miscellaneous Preprocessing Directives
  707. ======================================
  708.    This section describes three additional preprocessing directives.
  709. They are not very useful, but are mentioned for completeness.
  710.    The "null directive" consists of a `#' followed by a Newline, with
  711. only whitespace (including comments) in between.  A null directive is
  712. understood as a preprocessing directive but has no effect on the
  713. preprocessor output.  The primary significance of the existence of the
  714. null directive is that an input line consisting of just a `#' will
  715. produce no output, rather than a line of output containing just a `#'.
  716. Supposedly some old C programs contain such lines.
  717.    The ANSI standard specifies that the `#pragma' directive has an
  718. arbitrary, implementation-defined effect.  In the GNU C preprocessor,
  719. `#pragma' directives are not used, except for `#pragma once' (*note
  720. Once-Only::.).  However, they are left in the preprocessor output, so
  721. they are available to the compilation pass.
  722.    The `#ident' directive is supported for compatibility with certain
  723. other systems.  It is followed by a line of text.  On some systems, the
  724. text is copied into a special place in the object file; on most systems,
  725. the text is ignored and this directive has no effect.  Typically
  726. `#ident' is only used in header files supplied with those systems where
  727. it is meaningful.
  728. File: cpp.info,  Node: Output,  Next: Invocation,  Prev: Other Directives,  Up: Top
  729. C Preprocessor Output
  730. =====================
  731.    The output from the C preprocessor looks much like the input, except
  732. that all preprocessing directive lines have been replaced with blank
  733. lines and all comments with spaces.  Whitespace within a line is not
  734. altered; however, a space is inserted after the expansions of most
  735. macro calls.
  736.    Source file name and line number information is conveyed by lines of
  737. the form
  738.      # LINENUM FILENAME FLAGS
  739. which are inserted as needed into the middle of the input (but never
  740. within a string or character constant).  Such a line means that the
  741. following line originated in file FILENAME at line LINENUM.
  742.    After the file name comes zero or more flags, which are `1', `2' or
  743. `3'.  If there are multiple flags, spaces separate them.  Here is what
  744. the flags mean:
  745.      This indicates the start of a new file.
  746.      This indicates returning to a file (after having included another
  747.      file).
  748.      This indicates that the following text comes from a system header
  749.      file, so certain warnings should be suppressed.
  750.